﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading.Tasks;

namespace SkypeTranslater.Windows
{
	/// <summary>
	/// Interaction logic for QuickTranslateWindow.xaml
	/// </summary>
	public partial class QuickTranslateWindow 
	{
		public static RoutedCommand TranslateCommand = new RoutedCommand();

		public QuickTranslateWindow()
		{
			InitializeComponent();

			this.CommandBindings.Add(new CommandBinding(TranslateCommand, (send, arg) =>
				{
					var request = new TranslateServiceReference.TranslationRequest();
					request.FromLanguage = (cmbFromLang.SelectedItem as ComboBoxItem).Content as string;
					request.ToLanguage = (cmbToLang.SelectedItem as ComboBoxItem).Content as string;
					request.Content = txtFroTranslate.Text;

					Task translateTask = new Task(new Action(() =>
						{
							using (SkypeTranslater.TranslateServiceReference.TranslateServiceClient client = new TranslateServiceReference.TranslateServiceClient())
							{
								var response = client.Translate(request);

								if (response != null)
								{
									if(!Dispatcher.CheckAccess())
									this.Dispatcher.BeginInvoke(new Action(() =>
												{
													txtTranslResult.Text = response.TranslationResult;
												}), System.Windows.Threading.DispatcherPriority.Send);
									else
										txtTranslResult.Text = response.TranslationResult;
								}
							}
						}), TaskCreationOptions.LongRunning);

					translateTask.Start();

					translateTask.ContinueWith(prevTask=>
						{
							App.Log.Error("Error occurred while translating data",prevTask.Exception);
							prevTask.Dispose();
						}, TaskContinuationOptions.NotOnRanToCompletion);
				}, (sen, arg) => arg.CanExecute = true));
			
			this.InputBindings.Add(new KeyBinding(TranslateCommand, new KeyGesture(Key.T, ModifierKeys.Control)));
			btnTranslate.Command = TranslateCommand;
		}
	}
}
